package org.atovio.coolexam.controller.teacher;

import org.atovio.coolexam.annotation.AuthAccess;
import org.atovio.coolexam.common.Result;
import org.atovio.coolexam.common.Role;
import org.atovio.coolexam.entity.User;
import org.atovio.coolexam.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController("TeacherIndexController")
@RequestMapping("/teacher/index")
public class IndexController {

    private final UserService userService;

    @Autowired
    public IndexController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 验证登录, 需要为service指定用户身份role
     *
     * @param user 前端数据
     * @return 验证结果
     */
    @AuthAccess
    @PostMapping("/sessions")
    public Result login(@Validated @RequestBody User user) {
        // 传入前端数据和身份role
        // 返回包含token的数据
        user = userService.login(user, Role.T);
        return Result.success(user);
    }

    /**
     * 注册账户
     *
     * @param user 前端数据
     * @return 验证结果
     */
    @AuthAccess
    @PostMapping("/users")
    public Result register(@Validated @RequestBody User user) {
        // 传入前端数据和身份role
        user = userService.register(user, Role.A);
        return Result.success(user);
    }

    /**
     * 注册账户
     *
     * @param user 前端数据
     * @return 密码重置结果
     */
    @AuthAccess
    @PutMapping("/password")
    public Result resetPassword(@Validated @RequestBody User user) {
        return Result.success(userService.resetPassword(user));
    }
}
